package com.cd.javacxy.module.web.controller;

import com.cd.javacxy.common.model.entity.*;
import com.cd.javacxy.common.model.enums.DateTimePatternEnum;
import com.cd.javacxy.common.model.enums.ResponseCode;
import com.cd.javacxy.common.model.enums.TopicType;
import com.cd.javacxy.common.model.enums.VoteType;
import com.cd.javacxy.common.model.query.CategoryQuery;
import com.cd.javacxy.common.model.query.TopicQuery;
import com.cd.javacxy.common.model.vo.AjaxResponse;
import com.cd.javacxy.common.model.vo.CxyCategoryVo;
import com.cd.javacxy.common.utils.CategoryCache;
import com.cd.javacxy.common.utils.Constants;
import com.cd.javacxy.common.utils.DateUtil;
import com.cd.javacxy.common.utils.PageResult;
import com.cd.javacxy.exception.BussinessException;
import com.cd.javacxy.module.base.BaseController;
import com.cd.javacxy.module.web.service.CxyCategoryService;
import com.cd.javacxy.module.web.service.CxyTopicService;
import com.cd.javacxy.module.web.service.CxyTopicVoteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * CxyTopic的路由接口服务
 *
 * @author yanghy
 */
@Controller
@RequestMapping("/tp")
@Slf4j
public class CxyTopicController extends BaseController {

    private CxyCategoryService cxyCategoryService;

    private CxyTopicService topicService;

    private CategoryCache categoryCache;

    private CxyTopicVoteService topicVoteService;

    @Autowired
    public void setCxyCategoryService(CxyCategoryService cxyCategoryService) {
        this.cxyCategoryService = cxyCategoryService;
    }

    @Autowired
    public void setTopicService(CxyTopicService topicService) {
        this.topicService = topicService;
    }

    @Autowired
    public void setCategoryCache(CategoryCache categoryCache) {
        this.categoryCache = categoryCache;
    }

    @Autowired
    public void setTopicVoteService(CxyTopicVoteService topicVoteService) {
        this.topicVoteService = topicVoteService;
    }

    @GetMapping("")
    public ModelAndView bbs() {
        ModelAndView view = new ModelAndView("bbs/bbs");
        CategoryQuery categoryQuery = new CategoryQuery();
        Date date = new Date();
        String curDate = DateUtil.format(date, DateTimePatternEnum.YYYY_MM_DD.getPattern());
        categoryQuery.setStartDate(curDate);
        categoryQuery.setEndDate(curDate);
        view.addObject("categories", cxyCategoryService.findCategory4TopicCount(categoryQuery));
        view.addObject("activeUser", this.topicService.findActiveUsers());
        //获取总贴子数
        view.addObject("count", this.topicService.findCount(null));
        //获取今日贴子
        TopicQuery topicQuery = new TopicQuery();
        topicQuery.setStartDate(curDate);
        topicQuery.setEndDate(curDate);
        view.addObject("today", this.topicService.findCount(topicQuery));
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        topicQuery.setStartDate(DateUtil.format(calendar.getTime(), DateTimePatternEnum.YYYY_MM_DD.getPattern()));
        topicQuery.setEndDate(DateUtil.format(calendar.getTime(), DateTimePatternEnum.YYYY_MM_DD.getPattern()));
        Integer yesterdayCount = this.topicService.findCount(topicQuery);
        view.addObject("yesterdayCount", yesterdayCount);
        return view;
    }

    @GetMapping("/{topicId}")
    public ModelAndView bbsDetail(@PathVariable Integer topicId) {
        ModelAndView view = new ModelAndView("bbs/bbs_detail");
        try {
            CxyTopic topic = this.topicService.showTopic(topicId);
            view.addObject("topic", topic);
        } catch (Exception e) {
            log.error("贴子加载出错", e);
            view.setViewName("redirect:" + Constants.ERROR_404);
        }
        return view;
    }

    @GetMapping("/pre/public")
    public ModelAndView prePublicTopic(HttpSession session) {
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        if (sessionUser != null) {
            ModelAndView view = new ModelAndView("/page/login");
            return view;
        }
        ModelAndView view = new ModelAndView("bbs/publicTopic");
        CategoryQuery categoryQuery = new CategoryQuery();
        categoryQuery.setShowInBbs(Constants.Y);
        view.addObject("topicType", TopicType.values());
        view.addObject("voteType", VoteType.values());
        return view;
    }

    @ResponseBody
    @GetMapping("/categories")
    public AjaxResponse<List<CxyCategoryVo>> loadCategories() {
        try {
            return AjaxResponse.ok(this.categoryCache.getBbsCategories());
        } catch (Exception e) {
            log.error("加载分类出错", e);
        }
        return AjaxResponse.error("加载分类出错");
    }

    @ResponseBody
    @RequestMapping("/publish")
    public AjaxResponse<Integer> publishTopic(HttpSession session, CxyTopic topic, CxyTopicVote topicVote, String[] voteContent, CxyAttachment attachment) {
        AjaxResponse<Integer> ajaxResponse;
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        try {
            this.setUserBaseInfo(Topic.class, topic, session);
            this.topicService.addTopic(topic, topicVote, voteContent, attachment);
            ajaxResponse = AjaxResponse.ok(topic.getTopicId());
        } catch (BussinessException e) {
            ajaxResponse = AjaxResponse.error(ResponseCode.BUSSINESSERROR.getCode(), e.getLocalizedMessage());
            log.error("{}发表帖子失败", sessionUser.getUserName());
        } catch (Exception e) {
            ajaxResponse = AjaxResponse.error("服务器出错,帖子发表失败");
            log.error("{}发表帖子失败", sessionUser.getUserName());
        }
        return ajaxResponse;
    }

    @GetMapping(value = "/board/{pCategoryId}")
    public ModelAndView board(@PathVariable Integer pCategoryId, TopicQuery topicQuery) {
        ModelAndView view = new ModelAndView("bbs/bbs_list");
        CxyCategoryVo pCategory = this.cxyCategoryService.findCategoryBypCategoryId(pCategoryId);
        view.addObject("pCategory", pCategory);

        PageResult<CxyTopic> result = this.topicService.findTopicByPage(topicQuery);
        view.addObject("result", result);

        //获取分类总贴子数
        TopicQuery query = new TopicQuery();
        query.setPCategoryId(pCategory.getCategoryId());
        view.addObject("count", this.topicService.findCount(query));
        //获取今日贴子数
        Date date = new Date();
        query.setStartDate(DateUtil.format(date, DateTimePatternEnum.YYYY_MM_DD.getPattern()));
        query.setEndDate(DateUtil.format(date, DateTimePatternEnum.YYYY_MM_DD.getPattern()));
        view.addObject("todayCount", this.topicService.findCount(query));
        return view;
    }


    @GetMapping(value = "/sub/board/{categoryId}")
    public ModelAndView subBoard(@PathVariable Integer categoryId, TopicQuery topicQuery) {
        ModelAndView view = new ModelAndView("bbs/bbs_list");
        CxyCategoryVo pCategory = this.cxyCategoryService.findCategoryByCategoryId(categoryId);
        view.addObject("pCategory", pCategory);
        view.addObject("category", CategoryCache.getCategoryById(categoryId));
        PageResult<CxyTopic> result = this.topicService.findTopicByPage(topicQuery);
        view.addObject("result", result);
        //获取分类总贴子数
        TopicQuery query = new TopicQuery();
        query.setPCategoryId(pCategory.getCategoryId());
        view.addObject("count", this.topicService.findCount(query));
        //获取今日贴子数
        Date date = new Date();
        query.setStartDate(DateUtil.format(date, DateTimePatternEnum.YYYY_MM_DD.getPattern()));
        query.setEndDate(DateUtil.format(date, DateTimePatternEnum.YYYY_MM_DD.getPattern()));
        view.addObject("todayCount", this.topicService.findCount(query));
        return view;
    }

    @ResponseBody
    @PostMapping("/load/vote")
    public AjaxResponse<Object> loadVote(HttpSession session, Integer topicId) {
        AjaxResponse<Object> ajaxResponse = AjaxResponse.builder().build();
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        Integer userId = null;
        try {
            userId = sessionUser == null ? null : sessionUser.getUserId();
            CxyTopicVote topicVote = this.topicVoteService.getTopicVote(topicId, userId);
            ajaxResponse.setData(topicVote);
            ajaxResponse.setCode(ResponseCode.SUCCESS.getCode());
        } catch (Exception e) {
            log.error("投票加载出错", e);
            ajaxResponse.setErrorMsg("投票加载失败");
            ajaxResponse.setCode(ResponseCode.SERVERERROR.getCode());
        }
        return ajaxResponse;
    }

    @ResponseBody
    @PostMapping("/do/vote")
    public AjaxResponse<Object> doVote(HttpSession session, TopicVote topicVote, Integer[] voteDtlId) {
        AjaxResponse<Object> ajaxResponse = AjaxResponse.builder().build();
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        if (sessionUser == null) {
            ajaxResponse.setCode(ResponseCode.BUSSINESSERROR.getCode());
            ajaxResponse.setErrorMsg("请先登录");
            return ajaxResponse;
        }
        try {
            CxyTopicVote topicVote2 = this.topicVoteService.doVote(topicVote.getVoteId(),
                    topicVote.getVoteType().getType(), voteDtlId, sessionUser.getUserId(), topicVote.getTopicId());
            ajaxResponse.setData(topicVote2);
            ajaxResponse.setCode(ResponseCode.SUCCESS.getCode());
        } catch (Exception e) {
            log.error("投票出错", e);
            ajaxResponse.setErrorMsg("投票失败");
            ajaxResponse.setCode(ResponseCode.SERVERERROR.getCode());
        }
        return ajaxResponse;
    }

    @ResponseBody
    @GetMapping("/user/topic")
    public AjaxResponse<Object> loadTopic(HttpSession session, TopicQuery topicQuery) {
        AjaxResponse<Object> ajaxResponse = AjaxResponse.builder().build();
        try {
            PageResult<CxyTopic> pageResult = this.topicService.findTopicByPage(topicQuery);
            ajaxResponse.setData(pageResult);
            ajaxResponse.setCode(ResponseCode.SUCCESS.getCode());
        } catch (Exception e) {
            log.error("加载帖子异常", e);
            ajaxResponse.setErrorMsg("加载帖子出错");
            ajaxResponse.setCode(ResponseCode.SERVERERROR.getCode());
        }
        return ajaxResponse;
    }

}
